﻿using System.Collections.Generic;
using Data;
using LoginUI.Tip;
using LoginUI.UI;
using UnityEngine.UI;

namespace LoginUI.Login
{
    public class RegisterPanel : BasePanel
    {
        // 取消按钮
        public Button btnCancel;

        public Button btnRegister;

        // 账号输入框
        public InputField inputAccount;
        public InputField inputPassword;
        private Dictionary<string, string> _registerData = new();
        private string _username;

        private string _password;

        // currentRegisterData 定义字典用于存储当前注册的数据

        public override void Init()
        {
            // 回显面板数据
            inputAccount.text = "";
            inputPassword.text = "";
            btnCancel.onClick.AddListener(OnCancelClick);
            btnRegister.onClick.AddListener(OnRegisterClick);
            inputAccount.onValueChanged.AddListener(OnAccountChange);
            inputPassword.onValueChanged.AddListener(OnPasswordChange);
        }

        private void OnAccountChange(string UN)
        {
            _username = UN;
        }

        private void OnPasswordChange(string PW)
        {
            _password = PW;
        }

        private void OnRegisterClick()
        {
            // _password _username 合法性校验
            if (_username == "" || _password == "")
            {
                var tipInfo = "账号或密码不能为空";
                var tipPanel = UIManager.Instance.ShowPanel<TipPanel>();
                tipPanel.ChangeInfo(tipInfo);
                return;
            }

            if (!validate.ValidateAccount(_username) || !validate.ValidatePassword(_password))
            {
                var tipInfo = "账号或密码不合法";
                var tipPanel = UIManager.Instance.ShowPanel<TipPanel>();
                tipPanel.ChangeInfo(tipInfo);
                return;
            }

            //LoginMgr.Instance.RegisterData.accountPasswordDict
            if (LoginMgr.Instance.RegisterData.registerInfo.ContainsKey(_username))
            {
                var tipInfo = "账号已存在";
                var tipPanel = UIManager.Instance.ShowPanel<TipPanel>();
                tipPanel.ChangeInfo(tipInfo);
                return;
            }

            // 注册成功 SaveRegisterData
            // _registerData.Add(_username, _password);
            LoginMgr.Instance.SaveRegisterData(_username, _password);
            var successTipInfo = "注册成功!";
            var successTipPanel = UIManager.Instance.ShowPanel<TipPanel>();
            successTipPanel.ChangeInfo(successTipInfo);
            // 如何异步执行后面代码,即确定后自动返回登录界面??
            LoginMgr.Instance.ClearLoginData();
        }

        private void OnCancelClick()
        {
            LoginMgr.Instance.LoginData.isAuto = false;
            UIManager.Instance.HidePanel<RegisterPanel>();
            UIManager.Instance.ShowPanel<LoginPanel>();
        }
    }
}